from fastapi import UploadFile, File, Form, APIRouter, Depends
from fastapi.responses import JSONResponse
from qcloud_cos import CosConfig, CosS3Client
from uuid import uuid4
import os

from sqlalchemy.testing.pickleable import User

from models.user_models import *

from services.auth_service import require_user

import config

router = APIRouter()

# === 腾讯云配置 ===
SECRET_ID = config.TENCENT_SECRET_ID
SECRET_KEY = config.TENCENT_SECRET_KEY
REGION = "ap-beijing"
BUCKET = config.TENCENT_BUCKET  # 包含数字后缀
BASE_URL = f"https://{BUCKET}.cos.{REGION}.myqcloud.com"

config = CosConfig(Region=REGION, SecretId=SECRET_ID, SecretKey=SECRET_KEY, Token=None)
client = CosS3Client(config)

# === 上传接口 ===
@router.post("/upload_photo")
async def upload_photo(file: UploadFile = File(...),user: User = Depends(require_user(UserType.ADMIN))):

    print("upload_photo is called")

    ext = os.path.splitext(file.filename)[1]
    filename = f"{uuid4().hex}{ext}"
    file_bytes = await file.read()

    try:
        client.put_object(
            Bucket=BUCKET,
            Body=file_bytes,
            Key=f"doctor_image/{filename}",
            ContentType=file.content_type,
        )
        url = f"{BASE_URL}/doctor_image/{filename}"
        return {"url": url}
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})

# === 删除接口 ===
@router.post("/delete_photo")
async def delete_photo(filename: str = Form(...),user: User = Depends(require_user(UserType.ADMIN))):
    print("delete_photo is called")

    try:
        # key = url.split(f"{BASE_URL}/")[-1]
        key=f"doctor_image/{filename}"
        print(key)
        client.delete_object(Bucket=BUCKET, Key=key)
        return {"message": "deleted"}
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})
